using System;
using System.Drawing;
using MonoTouch.UIKit;
using Ro.Norc.ServiceStackClient;
using Ro.Norc.ServiceStackClientHello.ServiceModel.Operations;

namespace Ro.Norc.ServiceStackClientHello
{
	public class HelloViewController : UIViewController
	{
		private Service<HelloResponse> helloService = null;
		
		private ServiceEncoderJson jsonEncoder = null;
		
		private ServiceEncoderXml xmlEncoder = null;
		
		private UIButton wJsonButton = null;
		
		private UIButton wXmlButton = null;
		
		public HelloViewController () : base()
		{
			return;
		}
		
		private void ToggleLoading(bool loading)
		{
			UIApplication.SharedApplication.NetworkActivityIndicatorVisible = loading;
			
			wXmlButton.Enabled = !loading;
			wJsonButton.Enabled = !loading;
		}
		
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();
			
			jsonEncoder = new ServiceEncoderJson();
			xmlEncoder = new ServiceEncoderXml();
			
			helloService = new Service<HelloResponse>("http://www.servicestack.net/ServiceStack.Hello/servicestack");
			helloService.ServiceResult += delegate(object sender, ServiceResultArgs<HelloResponse> args) {
				ToggleLoading(false);
				UIAlertView response = new UIAlertView("Response", args.Result.Result, null, "Ok", null);
				response.Show();
			};
			helloService.ServiceError += delegate(object sender, ServiceErrorArgs args) {
				ToggleLoading(false);
				UIAlertView error = new UIAlertView("Error", "An error occured", null, "Ok", null);
				error.Show();
			};
			
			wJsonButton = UIButton.FromType(UIButtonType.RoundedRect);
			wJsonButton.SetTitle("Send hello request /w JSON", UIControlState.Normal);
			wJsonButton.Frame = new RectangleF(View.Frame.Width / 2 - 150, View.Frame.Height / 2 - 15, 300, 30);
			wJsonButton.TouchDown += delegate(object sender, EventArgs e) {
				ToggleLoading(true);
				helloService.Encoder = jsonEncoder;
				helloService.Send(new Hello() {
					Name = "Touchstack Client /w JSON"
				});
			};
			
			wXmlButton = UIButton.FromType(UIButtonType.RoundedRect);
			wXmlButton.SetTitle("Send hello request /w XML", UIControlState.Normal);
			wXmlButton.Frame = new RectangleF(wJsonButton.Frame.X, wJsonButton.Frame.Y + 35, 300, 30);
			wXmlButton.TouchDown += delegate(object sender, EventArgs e) {
				ToggleLoading(true);
				helloService.Encoder = xmlEncoder;
				helloService.Send(new Hello() {
					Name = "Touchstack Client /w XML"
				});
			};
			
			View.BackgroundColor = UIColor.White;
			View.AddSubview(wJsonButton);
			View.AddSubview(wXmlButton);
		}
	}
}